import json

from django.shortcuts import render
from patients.models import PatientModel
from patients.serializers import PatientModelSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework import status
from rest_framework.generics import RetrieveAPIView, DestroyAPIView
from doctors.models import AnswerModel, AnswerImageModel
from django_redis import get_redis_connection


class PatientAPIView(APIView):
    permission_classes = [IsAuthenticated, ]

    def get(self, request):
        user_id = request.user.id
        patient_list = PatientModel.objects.filter(user_id=user_id)
        ser = PatientModelSerializer(instance=patient_list, many=True)
        return Response({'message': '患者信息查询成功！', 'data': ser.data}, status=status.HTTP_200_OK)

    def post(self, request):
        ser = PatientModelSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'message': '患者信息添加成功！', 'data': ser.data}, status=status.HTTP_200_OK)
        return Response({'message': '患者信息添加失败！', 'data': ser.errors}, status=status.HTTP_400_BAD_REQUEST)

    def put(self, request, pk):
        user_id = request.user.id
        patient = PatientModel.objects.filter(id=pk, user_id=user_id).first()
        ser = PatientModelSerializer(instance=patient, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'message': '患者信息修改成功！', 'data': ser.data}, status=status.HTTP_200_OK)
        return Response({'message': '患者信息修改失败！', 'data': ser.errors}, status=status.HTTP_400_BAD_REQUEST)


class PatientRetrieveAPIView(RetrieveAPIView):
    queryset = PatientModel.objects.all()
    serializer_class = PatientModelSerializer


class PatientDestroyAPIView(DestroyAPIView):
    queryset = PatientModel.objects.all()
    serializer_class = PatientModelSerializer


# 问题和患者信息订单生成
class SavePatientAnswerAPIView(APIView):
    permission_classes = [IsAuthenticated, ]

    def post(self, request):
        user_id = request.user.id
        question = request.data.get('question')
        doctor_id = request.data.get('doctor')
        patients_id = request.data.get('patients_id')
        image_list = request.data.getlist('imageList[]')
        redis = get_redis_connection("answer")
        answer_info = redis.hgetall(f'{user_id}:{doctor_id}:{patients_id}:1')
        if answer_info:
            answer_patients_id = redis.hget(f'{user_id}:{doctor_id}:{patients_id}:1', 'patients_id').decode()
            print(answer_patients_id)
            print(patients_id)
            is_commit = redis.hget(f'{user_id}:{doctor_id}:{patients_id}:1', 'is_commit').decode()
            print(is_commit)
            if answer_patients_id == patients_id and is_commit == '0':
                answer_id = redis.hget(f'{user_id}:{doctor_id}:{patients_id}:1', 'answer_id').decode()
                answer = AnswerModel.objects.filter(id=answer_id).first()
                answer.user_content = question
                answer.save()
                redis_image_list = redis.hget(f'{user_id}:{doctor_id}:{patients_id}:1', 'image_list').decode()
                image_id_list = [int(i['image']) for i in json.loads(redis_image_list)]
                for i in image_id_list:
                    answer_image = AnswerImageModel.objects.filter(id=i).first()
                    answer_image.delete()
                redis.delete(f'{user_id}:{doctor_id}:{patients_id}:1')
                answer_dict = {
                    'answer_id': answer_id,
                    'content': question,
                    'is_commit': 0,
                    'patients_id': patients_id
                }
                answer_image_list = []
                for i in image_list:
                    answer_image = AnswerImageModel.objects.create(
                        image=i,
                        answer_id=answer_id
                    )
                    answer_image_list.append({'image': answer_image.id})
                answer_dict['image_list'] = json.dumps(answer_image_list)
                pipe = redis.pipeline()
                pipe.multi()
                redis.hset(f'{user_id}:{doctor_id}:{patients_id}:1', mapping=answer_dict)
                # 最终写入redis
                pipe.execute()
                return Response({"message": "问题已经存在，直接修改！"}, status=status.HTTP_200_OK)
            else:
                return Response({'message': '问题已经被提交，不能再次提交'}, status=status.HTTP_200_OK)
        else:
            answer = AnswerModel.objects.create(
                user_content=question,
                user_id=user_id,
                doctor_id=doctor_id,
                patients_id=patients_id,
            )
            answer_dict = {
                'answer_id': answer.id,
                'content': question,
                'is_commit': 0,
                'patients_id': patients_id
            }
            answer_image_list = []
            for i in image_list:
                answer_image = AnswerImageModel.objects.create(
                    image=i,
                    answer_id=answer.id
                )
                answer_image_list.append({'image': answer_image.id})
            answer_dict['image_list'] = json.dumps(answer_image_list)
            pipe = redis.pipeline()
            pipe.multi()
            redis.hset(f'{user_id}:{doctor_id}:{patients_id}:1', mapping=answer_dict)
            # 最终写入redis
            pipe.execute()
            return Response({"message": "问题提交成功"}, status=status.HTTP_200_OK)
